#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>

#define S_PORT 8080

int main(){

	int i,ret;
	int sfd;
	int cfd;
	char buf[BUFSIZ],c_IP[1024];
	socklen_t c_addr_len;
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;
	//1. socket
	sfd = socket(AF_INET,SOCK_STREAM,0);
	//2. bind	
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(S_PORT);
	s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(sfd,(struct sockaddr *)&s_addr,sizeof(s_addr));
	//3. litsen
	listen(sfd,1);
	//4. aceept
	c_addr_len = sizeof(c_addr);
	cfd = accept(sfd,(struct sockaddr *)&c_addr,&c_addr_len);
	if(cfd == -1){
		perror("accept");
		exit(0);
	}
	printf("client ip:%s,port:%d\n",
			inet_ntop(AF_INET,&(c_addr.sin_addr.s_addr),c_IP,sizeof(c_IP)),
			ntohs(c_addr.sin_port));

	while(1){
		//5. read
		ret = read(cfd,&buf,sizeof(buf));
		write(STDOUT_FILENO, buf, ret);
		//6. toupper
		for(i = 0;i<ret;i++)
			buf[i] = toupper(buf[i]);
		//7. write
		write(cfd,buf,ret);
	}
		//8. close
		close(sfd);
		close(cfd);
}
